/**
 * Copyright (c) 2020 kedacom
 * OpenATC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 * http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 **/
<template>
<div class="planContent">
  <div class="mask" v-if="maskVisible" @click ="clickMask"></div>
  <div class="btnGroup" v-show="false">
    <el-button class="btn" type="primary" @click="handleCreate">{{$t('openatc.greenwaveoptimize.generate')}}</el-button>
    <div class="editbtn" :style="{zIndex: zIndexObj.editZIndex}">
      <el-popover placement="top-start" trigger="manual" v-model="maskVisible" width="290">
        <div class="tipContent">
          <div>
            <i class="iconfont icon-yindaoicon1 handicon"></i>
          </div>
          <div class="text">{{$t('openatc.greenwaveoptimize.createconfig')}}</div>
        </div>
        <button slot="reference" class="btn" @click="handleEdit" ref="editbtn">{{$t('openatc.greenwaveoptimize.edit')}}</button>
      </el-popover>
    </div>
    <el-button class="btn" type="primary" @click="Download" style="margin-left:10px;">{{$t('openatc.button.download')}}</el-button>
  </div>
  <SchemeConfiguration
    :visible="configurationVisible"
    ref="config"
    :routeData="paramRoute"
    @emitLoading="emitLoading"
    @closeDrawer="closeDrawer" />
  <Messagebox :visible="messageboxVisible" :text="$t('openatc.greenwaveoptimize.confirmdownloadpattern')" @cancle="cancle" @ok="ok"/>
</div>
</template>

<script>
import SchemeConfiguration from './components/schemeConfiguration'
import PatternTable from './pattern/patternTable'
import PlanChart from './pattern/planChart/index'
// eslint-disable-next-line no-unused-vars
import { GetRouteInfo, getAllPatternOfRoute, getAllPhaseOfRoute, generateRoute, updateRoutePattern, clearRoutePattern, downloadRoutePattern, deleteRoutePattern, getBandwidth } from '../../api/route'
import Messagebox from '../../components/MessageBox/index'
import { getMessageByCode } from '../../utils/responseMessage'
import RouteUtil from './routeUtil.js'
export default {
  name: 'PlanContent',
  data () {
    return {
      timer: 0,
      activeName: 'first',
      activeName2: 'second',
      maskVisible: false, // 引导遮罩层是否显示
      configurationVisible: false, // 配置界面是否显示
      messageboxVisible: false, // 关闭界面二期确认弹窗是否显示
      addNum: 0,
      mock: [],
      paramRoute: {}, // 编辑route
      routeData: {}, // 单个协调路线的全部信息
      patternList: [],
      phaseList: [],
      greenwave: []
    }
  },
  components: {
    SchemeConfiguration,
    PatternTable,
    PlanChart,
    Messagebox
  },
  props: {
    compatibility: {
      type: Number,
      default: 1
    },
    schemeData: {
      type: Array
    },
    step: {
      type: Boolean
    },
    zIndexObj: {
      type: Object
    },
    routeId: {
      type: Number,
      default: 0
    }
  },
  watch: {
    schemeData: {
      handler: function (val) {
        if (val && !val.length && this.step) {
          this.maskVisible = true
          // 模拟一次手动点击，触发tip显示
          this.$refs.editbtn.click()
        }
      },
      deep: true
    }
  },
  mounted () {
  },
  destroyed () {
    this.closeInterval()
  },
  methods: {
    emitLoading (val) {
      this.$emit('emitLoading', val)
    },
    init (chooseId, editableTab) {
      if (this.chooseId !== chooseId) {
        // reset data
        this.patternList = []
        this.phaseList = []
        this.greenwave = []
      }
      this.chooseId = chooseId
      this.routeData = editableTab
      this.getAllPatternOfRoute()
    },
    getPatternListFromTab (tab, list) {
      let res = []
      let devs = tab.devs
      for (let dev of devs) {
        if (!dev.patternList || dev.patternList.length === 0) {
          res = list
          return res
        }
      }
      let devPatternList = devs.map(item => {
        let pattern = {
          agentid: item.agentid,
          feature: {
            patternList: item.patternList
          }
        }
        return pattern
      })
      res = devPatternList
      return res
    },
    getPhaseListFromTab (tab) {
      let res = []
      return res
    },
    closeInterval () {
      clearInterval(this.timer)
    },
    cancle () {
      this.messageboxVisible = false
    },
    ok () {
      this.messageboxVisible = false
      this.handleDownload()
    },
    Download () {
      this.messageboxVisible = true
    },
    handleClick (tab, event) {
      if (tab.name === 'first') {
        this.refreshChart()
      }
    },
    refreshChart () {
      let patterntable = this.$refs.patterntable
      let newPatternList = patterntable.newPatternList
      for (let pattern of this.patternList) {
        let agentid = pattern.agentid
        let newPattern = newPatternList.filter(npl => npl.agentid === agentid)[0]
        let patternId = newPattern.patternId
        let currPatternList = pattern.feature.patternList
        let currPattern
        if (Array.isArray(currPatternList)) {
          currPattern = currPatternList.filter(cpl => cpl.id === patternId)[0]
        } else {
          currPattern = currPatternList
        }
        currPattern.cycle = newPattern.cycle
        currPattern.offset = newPattern.offset
      }
      this.handlePlanChart()
    },
    handleAdd () {
      let paramRoute = {}
      this.paramRoute = paramRoute
      if (this.maskVisible && this.addNum <= 1) {
        if (this.addNum === 1) {
          this.maskVisible = false
        }
        this.addNum++
      } else {
        if (this.maskVisible) {
          this.addNum = 1
        }
      }
      if (!this.maskVisible) {
        this.routeData = []
        this.routeData = {}
        this.configurationVisible = true
        let _this = this
        this.$nextTick(() => {
          const config = _this.$refs.config
          if (config) {
            config.setDeviceData()
          }
        })
      }
    },
    handleEdit (paramRoute) {
      this.paramRoute = paramRoute
      if (this.maskVisible && this.addNum <= 1) {
        if (this.addNum === 1) {
          this.maskVisible = false
        }
        this.addNum++
      }
      if (!this.maskVisible) {
        this.configurationVisible = true
      }
    },
    getRouteInfo () {
      if (this.chooseId === 0) return
      GetRouteInfo(this.chooseId).then(res => {
        if (!res.data.success) {
          if (res.data.code === '4003') {
            let agentid = res.data.data.agentid
            this.$message.error(this.$t('openatc.greenwaveoptimize.device') + agentid + this.$t('openatc.greenwaveoptimize.notonline'))
            return
          }
          this.$message.error(getMessageByCode(res.data.code, this.$i18n.locale))
          return
        }
        this.routeData = res.data.data
        this.getAllPatternOfRoute() // 获取该路线的所有方案
      })
    },
    async handleDownload (id, routeData) {
      let param = {
        id: id,
        name: routeData.name,
        continueOnfailure: routeData.continueOnfailure,
        compatibility: routeData.compatibility,
        duration: routeData.duration,
        optPatternList: []
      }
      // check
      let generateData = this.getGenerateParam(routeData)
      let devList = []
      for (let dev of routeData.devs) {
        let feature = generateData.devs.filter(item => item.agentid === dev.agentid)[0].feature
        if (feature) {
          delete feature.phase
          dev.feature = feature
        }
        // 数据清洗
        // const targetItem = {
        //   'id': dev.id,
        //   'name': dev.name,
        //   'isused': dev.isused,
        //   'agentid': dev.agentid,
        //   'patternid': dev.patternid,
        //   'forwardphaseid': dev.forwardphaseid,
        //   'forwardphasedirection': dev.forwardphasedirection,
        //   'backphaseid': dev.backphaseid,
        //   'backphasedirection': dev.backphasedirection,
        //   'feature': dev.feature,
        //   'routeid': dev.routeid,
        //   'distance': dev.distance,
        //   'width': dev.width,
        //   'patterndes': dev.patterndes
        // }
        // dev.fixedtimeplanType = 'flow-split-opt'
        const targetItem = {...dev}
        delete targetItem.allPatterns
        delete targetItem.patternList
        delete targetItem.phaseList
        devList.push(targetItem)
      }
      routeData.devs = devList
      for (let dev of routeData.devs) {
        if (!dev.feature) {
          this.$message.warning(this.$t('openatc.greenwaveoptimize.errDownloadParam'), dev.agentid)
          return false
        }
      }
      param.optPatternList = [routeData]
      return new Promise((resolve, reject) => {
        downloadRoutePattern(param).then(res => {
          if (!res.data.success) {
            let msg = getMessageByCode(res.data.code, this.$i18n.locale)
            if (res.data.data) {
              let errorCode = res.data.data.errorCode
              if (errorCode) {
                msg = msg + ' - ' + getMessageByCode(errorCode, this.$i18n.locale)
              }
            }
            this.$message.error(msg)
            resolve(res)
          }
          this.$message.success(this.$t('openatc.greenwaveoptimize.planissuedsucc'), { type: 'success' })
          resolve(res)
        }).catch(error => {
          this.$message.error(error)
        })
      })
    },
    async handleDelete (param) {
      return new Promise((resolve, reject) => {
        resolve(true)
        // deleteRoutePattern(param).then(res => {
        //   if (!res.data.success) {
        //     let msg = getMessageByCode(res.data.code, this.$i18n.locale)
        //     if (res.data.data) {
        //       let errorCode = res.data.data.errorCode
        //       if (errorCode) {
        //         msg = msg + ' - ' + getMessageByCode(errorCode, this.$i18n.locale)
        //       }
        //     }
        //     this.$message.error(msg)
        //     resolve(false)
        //   }
        //   this.$message.success(this.$t('openatc.common.deletesuccess'))
        //   // this.$parent.getAllPlan()
        //   resolve(true)
        // }).catch(error => {
        //   this.$message.error(error)
        // })
      })
    },
    async handleClear (routeData) {
      return new Promise((resolve, reject) => {
        let param = {
          'routeid': routeData.id
        }
        clearRoutePattern(param).then(res => {
          if (!res.data.success) {
            let msg = getMessageByCode(res.data.code, this.$i18n.locale)
            if (res.data.data) {
              let errorCode = res.data.data.errorCode
              if (errorCode) {
                msg = msg + ' - ' + getMessageByCode(errorCode, this.$i18n.locale)
              }
            }
            this.$message.error(msg)
            resolve(false)
          }
          this.$message.success(this.$t('openatc.common.updatesuccess'))
          let copyRoute = JSON.parse(JSON.stringify(routeData))
          copyRoute.optPatternList = []
          const resRoute = copyRoute
          // this.$parent.getAllPlan(resRoute)
          this.$nextTick(() => {
            this.$parent.clear(resRoute)
          })
          // this.$parent.resetContentComponent(routeData)
          resolve(true)
        }).catch(error => {
          this.$message.error(error)
        })
      })
    },
    async handleSave (id, routeData) {
      return new Promise((resolve, reject) => {
        let param = this.getSaveParam(id, routeData)
        updateRoutePattern(param).then(res => {
          if (!res.data.success) {
            let msg = getMessageByCode(res.data.code, this.$i18n.locale)
            if (res.data.data) {
              let errorCode = res.data.data.errorCode
              if (errorCode) {
                msg = msg + ' - ' + getMessageByCode(errorCode, this.$i18n.locale)
              }
            }
            this.$message.error(msg)
            resolve(false)
          }
          this.$message.success(this.$t('openatc.common.savesuccess'))
          const resRoute = res.data.data
          this.$parent.getAllPlan(resRoute)
          resolve(true)
        }).catch(error => {
          this.$message.error(error)
        })
      })
    },
    handleSaveClick (id, routeData) {
      let param = this.getSaveParam(id, routeData)
      updateRoutePattern(param).then(res => {
        if (!res.data.success) {
          let msg = getMessageByCode(res.data.code, this.$i18n.locale)
          if (res.data.data) {
            let errorCode = res.data.data.errorCode
            if (errorCode) {
              msg = msg + ' - ' + getMessageByCode(errorCode, this.$i18n.locale)
            }
          }
          this.$message.error(msg)
          return
        }
        this.$message.success(this.$t('openatc.common.savesuccess'))
        this.$parent.getAllPlan()
      })
    },
    getSaveParam (id, tabs) {
      let routeData = JSON.parse(JSON.stringify(tabs))
      let targetPlanList = []
      for (let tab of routeData) {
        let devs = tab.devs
        let targetDevs = []
        for (let inter of devs) {
          let pList = inter.patternList ? inter.patternList : inter.feature.patternList
          let patternList = pList.map(item => {
            let pattern = {
              'id': item.id,
              'desc': item.desc,
              'offset': item.offset,
              'cycle': item.cycle,
              'contrloType': item.contrloType,
              'special': item.special,
              'rings': item.rings,
              'stages': item.stages,
              'stagesList': item.stagesList,
              'barriers': item.barriers
            }
            if (item.contrloType === 'stage') {
              pattern.rings = []
            }
            return pattern
          })
          // inter.id = param.id
          // delete inter.name
          // delete inter.content
          let dev = {
            'id': inter.id,
            'name': inter.name,
            'isused': inter.isused,
            'agentid': inter.agentid,
            'nextDistance': inter.nextDistance,
            'distance': inter.distance,
            'type': inter.type,
            'jsonparam': inter.jsonparam,
            'description': inter.description,
            // 'forwardphaseDesc': inter.forwardphaseDesc,
            // 'backphaseDesc': inter.backphaseDesc,
            'forwardphaseid': inter.forwardphaseid,
            'forwardphasedirection': inter.forwardphasedirection,
            'backphaseid': inter.backphaseid,
            'backphasedirection': inter.backphasedirection,
            // 'patternList': inter.patternList,
            'patternid': inter.patternid,
            'fixedtimeplantype': inter.fixedtimeplantype,
            'phases': inter.phases,
            'upspeed': inter.upspeed,
            'downspeed': inter.downspeed
          }
          inter = JSON.parse(JSON.stringify(dev))
          // inter.patternList = patternList
          inter.feature = {
            patternList: patternList
          }
          targetDevs.push(inter)
        }
        tab.devs = targetDevs
        let targetPlan = JSON.parse(JSON.stringify(tab))
        delete targetPlan.optPatternList
        targetPlanList.push(targetPlan)
      }
      // const target = JSON.parse(JSON.stringify(param))
      console.log(routeData)
      let param = {
        'id': id,
        'compatibility': this.compatibility,
        'optPatternList': targetPlanList
      }
      return param
    },
    async getBandwidth (routeData) {
      let param = this.getGenerateParam(routeData, 1)
      let greenwave = []
      await getBandwidth(param).then(res => {
        if (!res.data.success) {
          let msg = getMessageByCode(res.data.code, this.$i18n.locale)
          if (res.data.data) {
            let errorCode = res.data.data.errorCode
            if (errorCode) {
              msg = msg + ' - ' + getMessageByCode(errorCode, this.$i18n.locale)
            }
          }
          this.$message.error(msg)
          return
        }
        greenwave = res.data.data.greenwave
      })
      return greenwave
    },
    handleCreate (routeData) {
      let param = this.getGenerateParam(routeData, 1)
      generateRoute(param).then(res => {
        if (!res.data.success) {
          let msg = getMessageByCode(res.data.code, this.$i18n.locale)
          if (res.data.data) {
            let errorCode = res.data.data.errorCode
            if (errorCode) {
              msg = msg + ' - ' + getMessageByCode(errorCode, this.$i18n.locale)
            }
          }
          this.$message.error(msg)
          return
        }
        this.$message.success(this.$t('openatc.greenwaveoptimize.generatesuedsucc'))
        this.greenwave = res.data.data.greenwave
        this.patternList = res.data.data.devs
        for (let dev of routeData.devs) {
          for (let pattern of this.patternList) {
            if (dev.agentid === pattern.agentid) {
              dev.feature = pattern.feature
              dev.patternid = pattern.patternid
            }
          }
        }
        this.routeData = routeData
        this.handlePlanChart()
        this.handlePatternTable()
      })
    },
    getGenerateParam (routeData, bizType = 0) { // bizType： 1 generate专用
      let route = JSON.parse(JSON.stringify(routeData))
      let routeUtilObj = new RouteUtil(this.routeId, this.routeData, this.allPatternList)
      let param = routeUtilObj.getGenerateParam(route, bizType)
      return param
    },
    getAddFeatute (agentid, patternId) {
      let addPropertity = {
        barriers: [],
        stages: [],
        stagesList: []
      }
      for (let pdev of this.allPatternList) {
        if (pdev.agentid === agentid) {
          let pPatternList = pdev.feature.patternList
          let pPattern = pPatternList.find(pItem => pItem.id === patternId)
          if (pPattern) {
            addPropertity = {
              barriers: pPattern.barriers,
              stages: pPattern.stages,
              stagesList: pPattern.stagesList
            }
          }
          break
        }
      }
      return addPropertity
    },
    closeDrawer (isRefresh, resRoute) {
      this.configurationVisible = false
      if (isRefresh === 'refresh') {
        this.$emit('resetContentComponent', resRoute)
      }
    },
    clickMask () {
      this.maskVisible = false
    },
    getAllPatternOfRoute () {
      if (this.chooseId === 0) return
      getAllPatternOfRoute(this.chooseId).then(res => {
        if (!res.data.success) {
          let agentid = res.data.data.agentid
          let commomMsg = agentid ? this.$t('openatc.greenwaveoptimize.device') + agentid : ''
          let data = res
          let parrenterror = getMessageByCode(data.data.code, this.$i18n.locale)
          if (data.data.data) {
            // 子类型错误
            let childErrorCode = data.data.data.errorCode
            if (childErrorCode) {
              let childerror = getMessageByCode(data.data.data.errorCode, this.$i18n.locale)
              this.$message.error(parrenterror + ',' + childerror + ',' + commomMsg)
            }
          } else {
            this.$message.error(parrenterror + ',' + commomMsg)
          }
          this.$emit('ErrorOcurrred')
          return
        }
        this.allPatternList = res.data.data.devs
        let editableTab = this.routeData
        let patternList = this.getPatternListFromTab(editableTab, this.allPatternList)
        this.patternList = patternList
        this.getAllPhaseOfRouter() // 获取改路线的所有相位
      })
    },
    getAllPhaseOfRouter () {
      if (this.chooseId === 0) return
      getAllPhaseOfRoute(this.chooseId).then(res => {
        if (!res.data.success) {
          let agentid = res.data.data.agentid
          let commomMsg = agentid ? this.$t('openatc.greenwaveoptimize.device') + agentid : ''
          let data = res
          let parrenterror = getMessageByCode(data.data.code, this.$i18n.locale)
          if (data.data.data) {
            // 子类型错误
            let childErrorCode = data.data.data.errorCode
            if (childErrorCode) {
              let childerror = getMessageByCode(data.data.data.errorCode, this.$i18n.locale)
              this.$message.error(parrenterror + ',' + childerror + ',' + commomMsg)
            }
          } else {
            this.$message.error(parrenterror + ',' + commomMsg)
          }
          this.$emit('ErrorOcurrred')
          return
        }
        this.phaseList = res.data.data.devs
        this.handlePatternTable()
        this.handlePlanChart()
        this.handleMaskVisible()
      })
    },
    handlePatternTable () {
      this.$emit('handlePatternTable', this.routeData, this.patternList, this.phaseList)
    },
    handlePlanChart () {
      this.$emit('handlePlanChart', this.routeData, this.patternList, this.greenwave, this.allPatternList)
    },
    handleMaskVisible () {
      // 数据为空，显示蒙层
      if (this.patternList && !this.patternList.length && this.step) {
        this.maskVisible = true
        // 模拟一次手动点击，触发tip显示
        this.$refs.editbtn.click()
      }
    },
    onNewPatternListChange (newPatternList) {
      this.refreshChart()
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
